﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using University.Workshop.DataAccess;
using University.Workshop.Model;
using University.Workshop.Business;
using System.Collections.ObjectModel;
using System.Web.Security;
using System.Text;
using System.IO;

namespace University.Workshop.WebApp
{
    public partial class UserProfileCP : System.Web.UI.Page
    {
        private Collection<Product> allProducts;
        private Collection<Product> shownProducts;
        private const int MAX = 5;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            SetControls();
            GetData();
            GetPrivacySettings();              
        }

        private void GetPrivacySettings()
        {
            try
            {
                PrivacySetting privacySetting = PrivacySettingsManager.GetPrivacySettingByEmail(User.Identity.Name);
                if (!IsPostBack && privacySetting != null)
                {
                    status1.SelectedIndex = (privacySetting.Setting[0] - 48);
                    status2.SelectedIndex = (privacySetting.Setting[1] - 48);
                    status3.SelectedIndex = (privacySetting.Setting[2] - 48);
                    status4.SelectedIndex = (privacySetting.Setting[3] - 48);
                    status5.SelectedIndex = (privacySetting.Setting[4] - 48);
                    status6.SelectedIndex = (privacySetting.Setting[5] - 48);
                    status7.SelectedIndex = (privacySetting.Setting[6] - 48);
                    status8.SelectedIndex = (privacySetting.Setting[7] - 48);
                    showItems.SelectedIndex = (privacySetting.Setting[8] - 48);
                    showItems_SelectedIndexChanged(null, null);
                }
            }
            catch (Exception exc)
            {
                Response.Write("<script>alert('" + exc.Message + "'); window.location.href = 'UserCP.aspx';</script>");
            }
        }

        private void GetData()
        {
            try
            {
                User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
                if (user != null)
                {
                    TbFirstName.Text = user.PersonalInformation.FirstName;
                    TbLastName.Text = user.PersonalInformation.LastName;
                    TbGender.Text = (user.PersonalInformation.Gender == 'M' || user.PersonalInformation.Gender == 'm') ? "Male" : "Female";
                    TbBirthday.Text = user.PersonalInformation.Birthday.ToShortDateString();
                    TbPhone.Text = user.ContactInformation.Phone.ToString();
                    TbMobile.Text = user.ContactInformation.MobilePhone.ToString();
                    TbDepartment.Text = user.ContactInformation.Department;
                    TbCity.Text = user.ContactInformation.City;
                    allProducts = ProductDataAccess.GetProductsBySeller(user.Id, true);
                    if (!IsPostBack)
                    {
                        shownProducts = PrivacySettingsManager.GetShownProducts(user.Id);
                        Session["ShownProducts"] = shownProducts;
                        FillListBoxes();
                    }
                    if (Session["ShownProducts"] != null)
                        shownProducts = Session["ShownProducts"] as Collection<Product>;
                }
            }
            catch (Exception exc)
            {
                Response.Write("<script>alert('" + exc.Message + "'); window.location.href = 'UserCP.aspx';</script>");
            }
        }

        private void FillListBoxes()
        {
            var datasourceAllProds = from product in allProducts
                             where shownProducts.All(prod => prod.ProductId != product.ProductId)
                             select new
                             {
                                 Info = product.Name + " - " + product.Price + " " + product.Currency,
                                 Id = product.ProductId
                             };
            listBoxAllProducts.DataSource = datasourceAllProds;
            listBoxAllProducts.DataTextField = "Info";
            listBoxAllProducts.DataValueField = "Id";
            listBoxAllProducts.DataBind();
            var datasourceShownProds = from product in shownProducts
                                     select new
                                     {
                                         Info = product.Name + " - " + product.Price + " " + product.Currency,
                                         Id = product.ProductId
                                     };
            listBoxShownProducts.DataSource = datasourceShownProds;
            listBoxShownProducts.DataTextField = "Info";
            listBoxShownProducts.DataValueField = "Id";
            listBoxShownProducts.DataBind();
            btnAddProduct.Enabled = listBoxAllProducts.Items.Count != 0 && listBoxShownProducts.Items.Count < MAX;
            btnRemoveProduct.Enabled = listBoxShownProducts.Items.Count != 0;
            LblmaxProdInfo.Visible = listBoxShownProducts.Items.Count == MAX;
        }

        private void SetControls()
        {
            this.status1.Style.Add("display", "none");
            this.status2.Style.Add("display", "none");
            this.status3.Style.Add("display", "none");
            this.status4.Style.Add("display", "none");
            this.status5.Style.Add("display", "none");
            this.status6.Style.Add("display", "none");
            this.status7.Style.Add("display", "none");
            this.status8.Style.Add("display", "none");

            TbFirstName.Attributes.Add("onmouseover", "Show(1)");
            TbLastName.Attributes.Add("onmouseover", "Show(2)");
            TbGender.Attributes.Add("onmouseover", "Show(3)");
            TbBirthday.Attributes.Add("onmouseover", "Show(4)");
            TbPhone.Attributes.Add("onmouseover", "Show(5)");
            TbMobile.Attributes.Add("onmouseover", "Show(6)");
            TbDepartment.Attributes.Add("onmouseover", "Show(7)");
            TbCity.Attributes.Add("onmouseover", "Show(8)");
            dataList.Attributes.Add("onmouseover", "Show(9)");

            TbFirstName.Attributes.Add("onmouseout", "Hide(1)");
            TbLastName.Attributes.Add("onmouseout", "Hide(2)");
            TbGender.Attributes.Add("onmouseout", "Hide(3)");
            TbBirthday.Attributes.Add("onmouseout", "Hide(4)");
            TbPhone.Attributes.Add("onmouseout", "Hide(5)");
            TbMobile.Attributes.Add("onmouseout", "Hide(6)");
            TbDepartment.Attributes.Add("onmouseout", "Hide(7)");
            TbCity.Attributes.Add("onmouseout", "Hide(8)");

            TbFirstName.Attributes.Add("onclick", "ShowAndLock(1)");
            TbLastName.Attributes.Add("onclick", "ShowAndLock(2)");
            TbGender.Attributes.Add("onclick", "ShowAndLock(3)");
            TbBirthday.Attributes.Add("onclick", "ShowAndLock(4)");
            TbPhone.Attributes.Add("onclick", "ShowAndLock(5)");
            TbMobile.Attributes.Add("onclick", "ShowAndLock(6)");
            TbDepartment.Attributes.Add("onclick", "ShowAndLock(7)");
            TbCity.Attributes.Add("onclick", "ShowAndLock(8)");
            btnSelectProducts.Attributes.Add("onclick","ShowPopUp()");
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            String setting = "";
            setting = setting + status1.SelectedIndex.ToString() +
                      status2.SelectedIndex.ToString() +
                      status3.SelectedIndex.ToString() +
                      status4.SelectedIndex.ToString() +
                      status5.SelectedIndex.ToString() +
                      status6.SelectedIndex.ToString() +
                      status7.SelectedIndex.ToString() +
                      status8.SelectedIndex.ToString() +
                      showItems.SelectedIndex.ToString();
            try
            {
                PrivacySettingsManager.SetPrivacySettingByEmail(User.Identity.Name, setting);
                PrivacySettingsManager.SetShownProducts(shownProducts, allProducts, (showItems.SelectedIndex!=0));
                Response.Write("<script>alert('Settings saved successfully!'); window.location.href = 'UserProfileCP.aspx';</script>");
            }
            catch (Exception exc)
            {
                 Response.Write("<script>alert('" + exc.Message + "'); window.location.href = 'UserProfileCP.aspx';</script>");
            }
            
        }

        protected void showItems_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (showItems.SelectedIndex == 0)
            {
                LblInfo1.Visible = true;
                LblInfo2.Visible = false;
                dataList.DataSource = new Collection<Product>();
                dataList.DataBind();
                btnSelectProducts.Visible = false;
            }
            else
            {
                LblInfo1.Visible = false;
                if (shownProducts == null)
                {
                    LblInfo2.Visible = true;
                    dataList.DataSource = new Collection<Product>();
                }
                else
                {
                    LblInfo2.Visible = shownProducts.Count == 0;
                    dataList.DataSource = shownProducts;
                }
                dataList.DataBind();
                btnSelectProducts.Visible = true;
            }
        }

        protected void btnAddProduct_Click(object sender, EventArgs e)
        {
            if (shownProducts.Count < MAX)
            {
                if (listBoxAllProducts.Items.Count > 0)
                {
                    btnAddProduct.Enabled = true;
                    if (listBoxAllProducts.SelectedIndex != -1)
                    {
                        foreach (var prod in allProducts)
                        {
                            var selex = listBoxAllProducts.SelectedIndex.ToString();
                            if (prod.ProductId == long.Parse(listBoxAllProducts.SelectedValue.ToString()))
                            {
                                shownProducts.Add(prod);
                                break;
                            }
                        }
                        Session["ShownProducts"] = shownProducts;
                        FillListBoxes();
                    }
                }
            }
        }

        protected void btnRemoveProduct_Click(object sender, EventArgs e)
        {
            if (listBoxShownProducts.Items.Count > 0)
            {
                btnRemoveProduct.Enabled = true;
                if (listBoxShownProducts.SelectedIndex != -1)
                {
                    for (int i = 0; i < shownProducts.Count; i++)
                    {
                        if (shownProducts[i].ProductId == long.Parse(listBoxShownProducts.SelectedValue.ToString()))
                        {
                            shownProducts.RemoveAt(i);
                            break;
                        }
                    }
                    Session["ShownProducts"] = shownProducts;
                    FillListBoxes();
                }
            }
            else btnRemoveProduct.Enabled = false;
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            ModPopup.Hide();
            showItems_SelectedIndexChanged(null,null);
        }

        protected void btnSelectProducts_Click(object sender, EventArgs e)
        {
            FillListBoxes();
        }
    }
}
